"""
成品日程页面

按商品和日期管理成品的页面
"""

import tkinter as tk
from tkinter import ttk, messagebox
from pathlib import Path
import sys
from datetime import datetime, timedelta
import calendar

# 添加项目根目录到路径
project_root = Path(__file__).parent.parent.parent.parent
sys.path.insert(0, str(project_root))

from src.gui.main_app import BasePage
from src.gui.design_system import (DesignSystem, create_card_frame, 
                                  create_primary_button, create_secondary_button,
                                  create_success_button, create_danger_button)


class OutputSchedulePage(BasePage):
    """成品日程页面"""
    
    def __init__(self, parent, app):
        super().__init__(parent, app)
        self.current_date = datetime.now()
        self.schedule_data = {}
        
    def create_page(self):
        """创建页面内容"""
        self.frame = ttk.Frame(self.parent)
        
        # 页面标题
        self.create_header()
        
        # 主要内容区域
        self.create_main_content()
        
        # 加载示例数据
        self.load_sample_data()
    
    def create_header(self):
        """创建页面标题"""
        header_frame = ttk.Frame(self.frame)
        header_frame.pack(fill="x", pady=(0, DesignSystem.SPACING['xl']))
        
        # 标题区域
        title_container = ttk.Frame(header_frame)
        title_container.pack(side="left", fill="x", expand=True)
        
        title_label = ttk.Label(
            title_container,
            text="📅 成品日程",
            style='Title.TLabel'
        )
        title_label.pack(side="left")
        
        # 副标题
        subtitle_label = ttk.Label(
            title_container,
            text="按商品和日期管理成品制作计划",
            style='Muted.TLabel'
        )
        subtitle_label.pack(side="left", padx=(DesignSystem.SPACING['md'], 0))
        
        # 操作按钮区域
        action_frame = ttk.Frame(header_frame)
        action_frame.pack(side="right")
        
        # 返回按钮
        back_btn = create_secondary_button(
            action_frame,
            text="← 返回成品列表",
            command=lambda: self.app.show_page("output_management")
        )
        back_btn.pack(side="right")
    
    def create_main_content(self):
        """创建主要内容区域"""
        # 主内容容器
        main_container = ttk.Frame(self.frame)
        main_container.pack(fill="both", expand=True)
        
        # 左侧：日历和筛选
        self.create_left_panel(main_container)
        
        # 右侧：日程详情
        self.create_right_panel(main_container)
    
    def create_left_panel(self, parent):
        """创建左侧面板"""
        left_frame = ttk.Frame(parent)
        left_frame.pack(side="left", fill="both", expand=True, 
                       padx=(0, DesignSystem.SPACING['lg']))
        
        # 筛选工具栏
        self.create_filter_toolbar(left_frame)
        
        # 日历视图
        self.create_calendar_view(left_frame)
    
    def create_right_panel(self, parent):
        """创建右侧面板"""
        right_frame = ttk.Frame(parent, width=400)
        right_frame.pack(side="right", fill="y")
        right_frame.pack_propagate(False)
        
        # 选中日期详情
        self.create_date_details(right_frame)
        
        # 商品统计
        self.create_product_statistics(right_frame)
    
    def create_filter_toolbar(self, parent):
        """创建筛选工具栏"""
        toolbar_frame = create_card_frame(parent, "筛选和视图")
        toolbar_frame.pack(fill="x", pady=(0, DesignSystem.SPACING['xl']))
        
        # 第一行：商品筛选
        filter_row = ttk.Frame(toolbar_frame)
        filter_row.pack(fill="x", pady=(0, DesignSystem.SPACING['md']))
        
        # 商品筛选
        product_container = ttk.Frame(filter_row)
        product_container.pack(side="left")
        
        ttk.Label(product_container, text="商品筛选:", style='Heading.TLabel').pack(side="left")
        
        self.product_filter_var = tk.StringVar(value="all")
        product_combo = ttk.Combobox(
            product_container,
            textvariable=self.product_filter_var,
            values=["all", "时尚T恤", "运动鞋", "手提包", "面霜", "蓝牙耳机"],
            state="readonly",
            width=15
        )
        product_combo.pack(side="left", padx=(DesignSystem.SPACING['sm'], DesignSystem.SPACING['lg']))
        product_combo.bind("<<ComboboxSelected>>", self.on_filter_changed)
        
        # 状态筛选
        status_container = ttk.Frame(filter_row)
        status_container.pack(side="left")
        
        ttk.Label(status_container, text="状态筛选:", style='Heading.TLabel').pack(side="left")
        
        self.status_filter_var = tk.StringVar(value="all")
        status_combo = ttk.Combobox(
            status_container,
            textvariable=self.status_filter_var,
            values=["all", "📋 计划中", "🔄 制作中", "✅ 已完成", "📤 已发布"],
            state="readonly",
            width=12
        )
        status_combo.pack(side="left", padx=(DesignSystem.SPACING['sm'], 0))
        status_combo.bind("<<ComboboxSelected>>", self.on_filter_changed)
        
        # 第二行：视图控制
        view_row = ttk.Frame(toolbar_frame)
        view_row.pack(fill="x")
        
        # 月份导航
        month_nav = ttk.Frame(view_row)
        month_nav.pack(side="left")
        
        prev_btn = create_secondary_button(
            month_nav,
            text="◀",
            command=self.prev_month
        )
        prev_btn.pack(side="left", padx=(0, DesignSystem.SPACING['sm']))
        
        self.month_label = ttk.Label(
            month_nav,
            text=self.current_date.strftime("%Y年%m月"),
            style='Heading.TLabel'
        )
        self.month_label.pack(side="left", padx=(0, DesignSystem.SPACING['sm']))
        
        next_btn = create_secondary_button(
            month_nav,
            text="▶",
            command=self.next_month
        )
        next_btn.pack(side="left")
        
        # 今天按钮
        today_btn = create_primary_button(
            view_row,
            text="📅 今天",
            command=self.go_to_today
        )
        today_btn.pack(side="right")
    
    def create_calendar_view(self, parent):
        """创建日历视图"""
        calendar_frame = create_card_frame(parent, "日历视图")
        calendar_frame.pack(fill="both", expand=True)
        
        # 日历容器
        cal_container = ttk.Frame(calendar_frame)
        cal_container.pack(fill="both", expand=True, pady=DesignSystem.SPACING['md'])
        
        # 星期标题
        weekdays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
        for i, day in enumerate(weekdays):
            day_label = ttk.Label(
                cal_container,
                text=day,
                style='Heading.TLabel',
                anchor='center'
            )
            day_label.grid(row=0, column=i, sticky="ew", padx=1, pady=1)
        
        # 配置列权重
        for i in range(7):
            cal_container.grid_columnconfigure(i, weight=1)
        
        # 日期网格
        self.day_buttons = {}
        self.create_calendar_grid(cal_container)
    
    def create_calendar_grid(self, parent):
        """创建日历网格"""
        # 清除现有按钮
        for button in self.day_buttons.values():
            button.destroy()
        self.day_buttons.clear()
        
        # 获取当月日历
        year = self.current_date.year
        month = self.current_date.month
        cal = calendar.monthcalendar(year, month)
        
        # 创建日期按钮
        for week_num, week in enumerate(cal):
            for day_num, day in enumerate(week):
                if day == 0:
                    continue
                
                date_str = f"{year}-{month:02d}-{day:02d}"
                
                # 检查是否有日程
                has_schedule = date_str in self.schedule_data
                
                # 创建按钮
                if has_schedule:
                    btn_style = 'Primary.TButton'
                    btn_text = f"{day}\n●"
                else:
                    btn_style = 'Secondary.TButton'
                    btn_text = str(day)
                
                day_btn = ttk.Button(
                    parent,
                    text=btn_text,
                    style=btn_style,
                    command=lambda d=date_str: self.select_date(d)
                )
                day_btn.grid(row=week_num+1, column=day_num, sticky="nsew", padx=1, pady=1)
                
                self.day_buttons[date_str] = day_btn
        
        # 配置行权重
        for i in range(len(cal) + 1):
            parent.grid_rowconfigure(i, weight=1)
    
    def create_date_details(self, parent):
        """创建日期详情面板"""
        details_frame = create_card_frame(parent, "日期详情")
        details_frame.pack(fill="x", pady=(0, DesignSystem.SPACING['xl']))
        
        # 选中日期显示
        self.selected_date_label = ttk.Label(
            details_frame,
            text="请选择日期",
            style='Heading.TLabel'
        )
        self.selected_date_label.pack(pady=(0, DesignSystem.SPACING['md']))
        
        # 日程列表容器
        self.schedule_container = ttk.Frame(details_frame)
        self.schedule_container.pack(fill="x")
        
        # 默认提示
        self.create_default_schedule_view()
        
        # 操作按钮
        button_frame = ttk.Frame(details_frame)
        button_frame.pack(fill="x", pady=(DesignSystem.SPACING['md'], 0))
        
        add_schedule_btn = create_primary_button(
            button_frame,
            text="➕ 添加日程",
            command=self.add_schedule
        )
        add_schedule_btn.pack(side="left", padx=(0, DesignSystem.SPACING['sm']))
        
        edit_schedule_btn = create_secondary_button(
            button_frame,
            text="✏️ 编辑",
            command=self.edit_schedule
        )
        edit_schedule_btn.pack(side="left")
    
    def create_default_schedule_view(self):
        """创建默认日程视图"""
        self.default_schedule_frame = ttk.Frame(self.schedule_container)
        self.default_schedule_frame.pack(fill="x")
        
        hint_icon = ttk.Label(
            self.default_schedule_frame,
            text="📅",
            font=(DesignSystem.FONTS['family_primary'], 32),
            foreground=DesignSystem.COLORS['text_muted']
        )
        hint_icon.pack(pady=(DesignSystem.SPACING['lg'], DesignSystem.SPACING['sm']))
        
        hint_text = ttk.Label(
            self.default_schedule_frame,
            text="选择日期查看日程安排",
            style='Muted.TLabel'
        )
        hint_text.pack()
    
    def create_product_statistics(self, parent):
        """创建商品统计面板"""
        stats_frame = create_card_frame(parent, "商品统计")
        stats_frame.pack(fill="both", expand=True)
        
        # 统计数据
        stats_container = ttk.Frame(stats_frame)
        stats_container.pack(fill="both", expand=True, pady=DesignSystem.SPACING['md'])
        
        # 本月统计
        month_stats_frame = ttk.LabelFrame(stats_container, text="本月统计", padding=DesignSystem.SPACING['md'])
        month_stats_frame.pack(fill="x", pady=(0, DesignSystem.SPACING['md']))
        
        month_stats = [
            ("📋 计划任务", "15"),
            ("🔄 进行中", "8"),
            ("✅ 已完成", "12"),
            ("📤 已发布", "10")
        ]
        
        for i, (label, value) in enumerate(month_stats):
            stat_frame = ttk.Frame(month_stats_frame)
            stat_frame.pack(fill="x", pady=DesignSystem.SPACING['xs'])
            
            ttk.Label(stat_frame, text=label, style='Body.TLabel').pack(side="left")
            ttk.Label(stat_frame, text=value, style='Heading.TLabel').pack(side="right")
        
        # 商品排行
        ranking_frame = ttk.LabelFrame(stats_container, text="商品排行", padding=DesignSystem.SPACING['md'])
        ranking_frame.pack(fill="both", expand=True)
        
        rankings = [
            ("🥇 时尚T恤", "8个"),
            ("🥈 运动鞋", "6个"),
            ("🥉 手提包", "4个"),
            ("4️⃣ 面霜", "3个"),
            ("5️⃣ 蓝牙耳机", "2个")
        ]
        
        for product, count in rankings:
            rank_frame = ttk.Frame(ranking_frame)
            rank_frame.pack(fill="x", pady=DesignSystem.SPACING['xs'])
            
            ttk.Label(rank_frame, text=product, style='Body.TLabel').pack(side="left")
            ttk.Label(rank_frame, text=count, style='Muted.TLabel').pack(side="right")
    
    def load_sample_data(self):
        """加载示例数据"""
        # 示例日程数据
        today = datetime.now()
        sample_schedules = {}
        
        # 生成一些示例日程
        for i in range(10):
            date = today + timedelta(days=i-5)
            date_str = date.strftime("%Y-%m-%d")
            
            if i % 3 == 0:  # 每3天有一个日程
                sample_schedules[date_str] = [
                    {
                        'time': '09:00',
                        'product': '时尚T恤',
                        'task': '产品拍摄',
                        'status': '📋 计划中'
                    },
                    {
                        'time': '14:00',
                        'product': '运动鞋',
                        'task': '视频剪辑',
                        'status': '🔄 制作中'
                    }
                ]
        
        self.schedule_data = sample_schedules
        self.update_calendar()
    
    def update_calendar(self):
        """更新日历显示"""
        self.month_label.configure(text=self.current_date.strftime("%Y年%m月"))
        self.create_calendar_grid(self.calendar_frame.winfo_children()[0])
    
    def prev_month(self):
        """上一个月"""
        if self.current_date.month == 1:
            self.current_date = self.current_date.replace(year=self.current_date.year-1, month=12)
        else:
            self.current_date = self.current_date.replace(month=self.current_date.month-1)
        self.update_calendar()
    
    def next_month(self):
        """下一个月"""
        if self.current_date.month == 12:
            self.current_date = self.current_date.replace(year=self.current_date.year+1, month=1)
        else:
            self.current_date = self.current_date.replace(month=self.current_date.month+1)
        self.update_calendar()
    
    def go_to_today(self):
        """跳转到今天"""
        self.current_date = datetime.now()
        self.update_calendar()
        self.select_date(self.current_date.strftime("%Y-%m-%d"))
    
    def select_date(self, date_str):
        """选择日期"""
        # 更新选中日期显示
        date_obj = datetime.strptime(date_str, "%Y-%m-%d")
        self.selected_date_label.configure(text=date_obj.strftime("%Y年%m月%d日"))
        
        # 显示该日期的日程
        self.show_date_schedule(date_str)
    
    def show_date_schedule(self, date_str):
        """显示日期日程"""
        # 清除现有内容
        for widget in self.schedule_container.winfo_children():
            widget.destroy()
        
        # 获取该日期的日程
        schedules = self.schedule_data.get(date_str, [])
        
        if schedules:
            # 显示日程列表
            for schedule in schedules:
                schedule_item = ttk.Frame(self.schedule_container)
                schedule_item.pack(fill="x", pady=DesignSystem.SPACING['xs'])
                
                # 时间
                time_label = ttk.Label(
                    schedule_item,
                    text=schedule['time'],
                    style='Heading.TLabel'
                )
                time_label.pack(side="left")
                
                # 内容
                content_frame = ttk.Frame(schedule_item)
                content_frame.pack(side="left", fill="x", expand=True, padx=(DesignSystem.SPACING['md'], 0))
                
                ttk.Label(content_frame, text=f"{schedule['product']} - {schedule['task']}", style='Body.TLabel').pack(anchor="w")
                ttk.Label(content_frame, text=schedule['status'], style='Muted.TLabel').pack(anchor="w")
        else:
            # 显示空状态
            self.create_default_schedule_view()
    
    def on_filter_changed(self, event=None):
        """筛选条件改变"""
        # TODO: 实现筛选逻辑
        pass
    
    def add_schedule(self):
        """添加日程"""
        messagebox.showinfo("提示", "添加日程功能开发中...")
    
    def edit_schedule(self):
        """编辑日程"""
        messagebox.showinfo("提示", "编辑日程功能开发中...")
